<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'"
    :close-on-click-modal="false"
    append-to-body
    :visible.sync="visible"
    class="jsbos-dialog jsbos-dialog_center"
    lock-scroll
    width="600px"
  >
    <el-row :gutter="15" class="">
      <el-form
        ref="elForm"
        :model="dataForm"
        :rules="rules"
        size="small"
        label-width="120px"
        label-position="right"
      >
        <template>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <TreeSelect
                v-model="dataForm.parentId"
                :options="treeTypeData"
                :props="defaultTypeProps"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类编码" prop="code">
              <el-input
                v-model="dataForm.code"
                placeholder="请输入"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类名称" prop="name">
              <el-input
                v-model="dataForm.name"
                placeholder="请输入"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类描述" prop="description">
              <el-input
                v-model="dataForm.description"
                placeholder="请输入"
                clearable
                :style="{ width: '100%' }"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">
        确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import request from "@/utils/request";
import { isEmpty } from "@/utils/isEmpty";
import { getTypeListTree, getTypeList } from "../api";
export default {
  components: {},
  props: [],
  data() {
    // 查询编码重复
    const validateCode = (rule, value, callback) => {
      var form = {
        code: value,
        name: "",
      };
      getTypeList(form).then((response) => {
        var flag = response.data;
        if (!isEmpty(this.dataForm.id)) {
          if (
            isEmpty(flag) ||
            (flag.length == 1 && flag[0].id == this.dataForm.id)
          ) {
            callback();
          } else {
            callback(new Error("编码重复"));
          }
        } else {
          if (isEmpty(flag)) {
            callback();
          } else {
            callback(new Error("编码重复"));
          }
        }
      });
    };
    // 查询分类名称重复
    const validateName = (rule, value, callback) => {
      var form = {
        code: "",
        name: value,
      };
      getTypeList(form).then((response) => {
        var flag = response.data;
        if (!isEmpty(this.dataForm.id)) {
          if (
            isEmpty(flag) ||
            (flag.length == 1 && flag[0].id == this.dataForm.id)
          ) {
            callback();
          } else {
            callback(new Error("名称重复"));
          }
        } else {
          if (isEmpty(flag)) {
            callback();
          } else {
            callback(new Error("编码重复"));
          }
        }
      });
    };
    return {
      defaultTypeProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      treeTypeData: [],
      visible: false,
      loading: false,
      isDetail: false,
      dataForm: {
        code: "",
        name: "",
        parentId: "",
        description: "",
      },
      rules: {
        parentId: [
          {
            required: true,
            message: "上级分类不能为空",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "问卷调查类型编码不能为空",
            trigger: "blur",
          },
          { validator: validateCode, trigger: "blur" },
        ],
        name: [
          {
            required: true,
            message: "问卷调查类型名称不能为空",
            trigger: "blur",
          },
          { validator: validateName, trigger: "blur" },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getTypeListTree();
  },
  mounted() {},
  methods: {
    getTypeListTree() {
      var data = {
        parentId: "-1",
      };
      getTypeListTree(data).then((res) => {
        let _data = {
          id: "-1",
          name: "顶级节点",
        };
        this.treeTypeData = res.data;
        this.treeTypeData.unshift(_data);
      });
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },

    init(id, isDetail) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.isDetail = isDetail || false;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          request({
            url: "/api/questionnaire/OqQuestionnaireType/" + this.dataForm.id,
            method: "get",
          }).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
        }
      });
      this.getTypeListTree();
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          this.request();
        }
      });
    },
    request() {
      var _data = this.dataList();
      if (!this.dataForm.id) {
        request({
          url: "/api/questionnaire/OqQuestionnaireType",
          method: "post",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      } else {
        request({
          url: "/api/questionnaire/OqQuestionnaireType/" + this.dataForm.id,
          method: "PUT",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      this.dataForm = _dataAll;
    },
  },
};
</script>
